package com.tuo.controller;

import com.tuo.beans.Customer;
import com.tuo.service.CustomerService;
import org.hibernate.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tuo on 2016/1/9.
 */
@Controller
public class CustomerController {
    @Autowired
    CustomerService service;


    @ResponseBody
    @RequestMapping(value = "customer")
    public Map<String, Object> customer(Customer customer, int page, int rows, @RequestParam(required = false) String q) {
        if (StringHelper.isEmpty(q)) {
            customer.setName(q);
        }
        List<Customer> customers = null;
        try {
            customers = service.query(customer, true);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", customers.size());
        List<Customer> list = new ArrayList<Customer>();
        if (page == 0 && rows == 0) {
            map.put("rows", customers);
        } else {
            for (int i = (page - 1) * rows; i < customers.size() && i < (page * rows); i++) {
                list.add(customers.get(i));
            }
            map.put("rows", list);
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("saveCustomer")
    public Map<String, String> saveCustomer(Customer customer) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            service.save(customer);
            map.put("message", "success");
        } catch (Throwable e) {
            map.put("errorMsg", e.getMessage());
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("editCustomer")
    public Map<String, String> editCustomer(long id, Customer customer) {
        Map<String, String> map = new HashMap<String, String>();
        customer.setId(id);
        try {
            service.update(customer);
            map.put("message", "success");
        } catch (Throwable e) {
            e.printStackTrace();
            map.put("errorMsg", e.getMessage());
        }
        return map;
    }
}
